package com.example.publishDemo.Controller;

import com.example.publishDemo.Model.AjaxResult;
import com.example.publishDemo.Model.Tag;
import com.example.publishDemo.Service.TagService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin(origins = "http://localhost:8080")
@RestController
@RequestMapping("/tag")
public class TagController {

    @Resource
    TagService tagService;

    @GetMapping("/tags")
    public AjaxResult tags(){
        List<Tag> all = tagService.getAll();
        List<Object> a_tag = new ArrayList<>();
        for (Tag tag:all) {
            Map<String, Object> map = new HashMap<>();
            map.put("value", tag.getName());
            map.put("label", tag.getName());

            a_tag.add(map);
        }
        return AjaxResult.success(a_tag);
    }

    @GetMapping("/star")
    public AjaxResult star(@RequestParam int t_id, int u_id) {
        boolean focus = tagService.isFocus(u_id, t_id);
        if (focus) {
            tagService.unstar(u_id, t_id);
            return AjaxResult.error("已取消收藏");
        }
        tagService.star(u_id, t_id);
        return AjaxResult.success(true);
    }

    @GetMapping("/init")
    public AjaxResult init(@RequestParam int u_id){
        List<Tag> all = tagService.getAll();
        List<Object> a_tag = new ArrayList<>();

        for (int i = 0; i < all.size(); i++) {
            Map<String, Object> tagInfo = new HashMap<>();
            tagInfo.put("t_id", all.get(i).getT_id());
            tagInfo.put("name", all.get(i).getName());
            tagInfo.put("description", all.get(i).getDescription());
            tagInfo.put("picture", all.get(i).getPicture());

            boolean focus = tagService.isFocus(u_id, all.get(i).getT_id());
            tagInfo.put("relation", focus);
            tagInfo.put("people", tagService.allPeople(all.get(i).getT_id()));
            tagInfo.put("articles", tagService.allArticle(all.get(i).getName()));

            a_tag.add(tagInfo);
        }

        return AjaxResult.success(a_tag);
    }
}
